from django.shortcuts import render, redirect, reverse
from django.utils.decorators import method_decorator
from users.decorators import login_required
from django.views import View
from datetime import datetime
from .models import Course
from django.db.models import Q
from scores.models import Score
from .forms import CourseAddForm
from users.models import User


# 课程列表视图
@method_decorator(login_required, name='dispatch')
class CourseListView(View):
    @staticmethod
    def get(request, *args, **kwargs):
        user = request.front_user
        if user.css_role == 'student':
            date = datetime.now()
            # 找出当前时间还没到截止时间且是本学生学校开设的课程(学生没选过的课)
            courses = Course.objects.filter(Q(css_end_time__gte=date) & Q(css_school=user.css_school)
                                            & ~Q(score_course__css_student=user.id))
            return render(request, 'courses/course_list.html', context={'courses': courses, 'role': 'student'})
        elif user.css_role == 'teacher':
            courses = Course.objects.filter(css_teacher=user.id)
            return render(request, 'courses/course_list.html', context={'courses': courses, 'role': 'teacher'})
        elif user.css_role == "school":
            courses = Course.objects.filter(css_school=user.id)
            return render(request, 'courses/course_list.html', context={'courses': courses, 'role': 'school'})
        else:
            print("你不是本系统用户！")
            return redirect(reverse('users:register'))


# 学生已选课程列表视图
@method_decorator(login_required, name='dispatch')
class SelectedListView(View):
    @staticmethod
    def get(request, *args, **kwargs):
        user = request.front_user
        # 根据关联的教师，再通过分数表找到此学生
        courses = Course.objects.filter(css_teacher__score_teacher__css_student=user.id)
        return render(request, 'courses/selected_list.html', context={'courses': courses})


# 课程详情视图
@method_decorator(login_required, name='dispatch')
class CourseDetailView(View):
    @staticmethod
    def get(request, course_id, *args, **kwargs):
        course = Course.objects.get(pk=course_id)
        return render(request, 'courses/course_detail.html', context={'course': course})


# 学生选择课程
@method_decorator(login_required, name='dispatch')
class SelectCourseView(View):
    @staticmethod
    def get(request, course_id, *args, **kwargs):
        user = request.front_user
        if user.css_role == "student":
            course = Course.objects.get(pk=course_id)
            score_exist = Score.objects.filter(css_student=user.id, css_course=course.id).exists()
            if score_exist:
                print('您已经选了，不能重复选择')
                return redirect(reverse("courses:selected_list"))
            elif datetime.now() < course.css_start_time:
                print('选课时间还未到达')
                return redirect(reverse('courses:course_list'))
            elif course.css_num < course.css_max_num:
                score = Score(css_score=0, css_student=user, css_teacher=course.css_teacher, css_course=course)
                course.css_num += 1
                score.save()
                course.save()
                return redirect(reverse("courses:selected_list"))
            else:
                print('人数已满不可选！')
                return redirect(reverse('courses:course_list'))
        else:
            print('你不是学生！')
            return redirect(reverse('courses:course_list'))


# 学校增设课程
@method_decorator(login_required, name="dispatch")
class CourseAddView(View):
    @staticmethod
    def get(request, *args, **kwargs):
        form = CourseAddForm()
        school = request.front_user
        if school.css_role == 'school':
            teachers = User.objects.filter(css_school=school.id, css_role="teacher")
            return render(request, 'courses/course_add.html', context={'form': form, 'teachers': teachers})

    def post(self, request, *args, **kwargs):
        form = CourseAddForm(request.POST, request.FILES)
        school = request.front_user
        if form.is_valid() and school.css_role == "school":
            form.save()
            return redirect(reverse("courses:course_list"))
        else:
            print(form.errors.get_json_data())
            return redirect(reverse('courses:course_add'))


# 某课程学生列表视图
@method_decorator(login_required, name='dispatch')
class CourseStudentListView(View):
    @staticmethod
    def get(request, course_id, *args, **kwargs):
        user = request.front_user
        if user.css_role != "student":
            students = User.objects.filter(score_student__css_course=course_id)
            return render(request, 'courses/course_student_list.html', context={'students': students})
        else:
            print("您没有权限查看")
            return redirect(reverse("courses:course_list"))


# 学生取消选课/学校删除此课程
@method_decorator(login_required, name='dispatch')
class CourseDeleteView(View):
    @staticmethod
    def get(request, course_id, *args, **kwargs):
        user = request.front_user
        # 学生取消选课
        if user.css_role == "student":
            # 删除学分表的信息
            score = Score.objects.filter(css_course=course_id, css_student=user.pk)
            score.delete()
            # 更新课程表的选课人数
            course = Course.objects.get(pk=course_id)
            course.css_num -= 1
            course.save()
        # 学校删除课程
        elif user.css_role == "school":
            # 找出课程删除信息
            course = Course.objects.filter(pk=course_id)
            course.delete()
        else:
            print("您没有权限")
        return redirect(reverse("courses:course_list"))
